<?php
namespace app\spadmin\controller\education;
use app\common\controller\Backend;
use app\spadmin\library\Office;
use think\Request;
/**
 * 试题库
 */
class Exam extends Backend{

    protected $knowledge = null;
    protected $exam_type = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Exam');
        $this->knowledge = model('Knowledge')->where('status',1)->order('sort asc')->column('id,title,id,sort');
        $this->view->assign('knowledge',$this->knowledge);
        $this->exam_type = model('type')->where('status',1)->order('sort asc')->column('id,name,id,sort');
        $this->view->assign('type',$this->exam_type);
    }

    public function index(){
        $this->request->filter(['strip_tags', 'trim']);
        
        if($this->request->isAjax()){
            $data = $this->request->param();
            if (isset($data['keywords']) && $data['keywords']) {
                $map['title'] = ['like','%'.$data['keywords'].'%'];
            }
            if (isset($data['knowledge_id']) && $data['knowledge_id']) {
                $map['knowledge_id'] = $data['knowledge_id'];
            }
            if (isset($data['type']) && $data['type']) {
                $map['type_id'] = $data['type_id'];
            }
            if (isset($data['cate']) && $data['cate']) {
                $map['cate'] = $data['cate'];
            }
            if (isset($data['status']) && $data['status'] === '0') {
                $map['status'] = $data['status'];
            } else {
                $map['status'] = 1;
            }     
            $list =   $this->model->where($map)->order('id asc')->paginate($data['limit'])->toArray();
            return $this->result($list);
        }
        return $this->view->fetch();
    }

    public function edit($ids = NULL){
        $row = $this->model->get(['id'=>$ids]);
        if($this->request->isPost()){
            if($row == null){
                $row = $this->model;
            }
            $data = $this->request->post('',[],'strip_tags');
            if($data['cate'] <= 3 && $data['item']){
                $data['item'] = explode("\r\n",$data['item']);
                $data['answer'] = strtoupper(strip_tags($data['answer']));
            }
            $result = $row->validate()->allowField(true)->save($data,$data['id']?['id'=>$data['id']]:null);
            if($result === false){
                $this->error($row->getError());
            }
            $this->success('操作成功');
        }
        $this->assign('info',$row);
        return $this->view->fetch();
    }

    public function excle(){
        if($this->request->isPost()){
            $excle = $this->request->param('excle');
            $result = Office::excle($excle);
            if($result !== true){
                $this->error($result);
            }
            $this->success('导入成功');
        }
      
    }

    
}